//
//  NewScheduleController.m
//  EducationAdminClient
//
//  Created by 孙添凤 on 2018/2/11.
//  Copyright © 2018年 周佳兴. All rights reserved.
//
#define scorllViewCONheight 1000.0f

#import "NewScheduleController.h"

#import "CouModel.h"
#import "SubView.h"
#import "ClassDetailViewController.h"
#import "FDCalendar.h"
#import "ScheduleCell.h"
#import "ScheduleModel.h"
@interface NewScheduleController (){
    NSDate *_pickDate;
    NSString *_pickDateString;
    NSDate *_pickDateBefore;
    NSString *_pickDateBeforeString;
    TNCustomSegment *segment;
    UIView *navBarBtnBottom;
    UIButton *btn1;
    UIButton *btn2;
    UIView *calanderView;
    UITableView *tbView;
    XFDaterView*dater;
    
    FDCalendar *calendar;
    
    NSMutableArray *_data1;
    NSMutableArray *_data2;
    NSMutableArray *_data3;
    
    NSInteger _currentData1Index;
    NSInteger _currentData2Index;
    NSInteger _currentData3Index;
    
    NSInteger _currentData1SelectedIndex;
    JSDropDownMenu *menu;
    NSString *searchStart;
    NSString *searchEnd;
    
    NSMutableArray *seledayArr;
    BOOL isNew;//为NO不显示新版课程表 若要显示 需在viewdidload中设置为YES
    
    NSString *_returnNowDateString;
    NSDate *_returnNowDate;
}

@end
static const CGFloat MJDuration = 0.5;
static CGFloat CALENDER_VIEW_HEIGHT = 90;
@implementation NewScheduleController

-(void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:YES];
    self.cusTabView.hidden = NO;
    segment.hidden = NO;
}
-(void)viewDidAppear:(BOOL)animated{
    [super viewDidAppear:YES];
    self.cusTabView.userInteractionEnabled = YES;
    
    if ([self.navigationController respondsToSelector:@selector(interactivePopGestureRecognizer)])
    {
        self.navigationController.interactivePopGestureRecognizer.enabled = NO;
        self.navigationController.interactivePopGestureRecognizer.delegate = self;
    }
    
}

-(void)viewWillDisappear:(BOOL)animated{
    segment.hidden = YES;
}

//- (void)segment:(TNCustomSegment *)segment didSelectedIndex:(NSInteger)selectIndex{
//
//    self.selectIndex = selectIndex;
//    NSLog(@"%ld",(long)selectIndex);
//    if(selectIndex==0){
//        _requsetUrlSegment = KECHENGBIAO_URl;
//    }else{
//        _requsetUrlSegment = SHANGYUAN_SHADULE;
//    }
//
//}
//我的课表
-(void)btn1Click:(UIButton *)btn{
    
    NSLog(@"返回了 返回了");
    
    return;
    
    NSLog(@"btn1");
    [UIView animateWithDuration:0.3 animations:^{
        navBarBtnBottom.frame = CGRectMake(KWIDTH/2-90, 2.5, 90, 35);
    }];
    [btn2 setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [btn1 setTitleColor:[UIColor redColor] forState:UIControlStateNormal];
    //    calanderView.hidden = YES;
    [calanderView mas_updateConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.view.mas_top).offset(-45);
        make.bottom.equalTo(self.view.mas_bottom).offset(100);
    }];
    _ifBtn1 = YES;
    tbView.frame = CGRectMake(0, 52, [UIScreen mainScreen].bounds.size.width, [UIScreen mainScreen].bounds.size.height-60-70);
    [self dataRequest3];
    
}
//班级课表
-(void)btn2Click:(UIButton *)btn{
    NSLog(@"btn2");
    [UIView animateWithDuration:0.3 animations:^{
        navBarBtnBottom.frame = CGRectMake(KWIDTH/2, 2.5, 90, 35);
    }];
    [btn1 setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [btn2 setTitleColor:[UIColor redColor] forState:UIControlStateNormal];
    [calanderView mas_updateConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.view.mas_top);
        make.bottom.equalTo(self.view.mas_bottom);
    }];
    calanderView.hidden = NO;
    _ifBtn1 = NO;
    tbView.frame = CGRectMake(0, 52, [UIScreen mainScreen].bounds.size.width, [UIScreen mainScreen].bounds.size.height-60-44-70);
    [self dataRequest2];
}

-(void)viewDidLoad{
    [super viewDidLoad];
    [self setTitleLabelText:@"我的课程"];
    _timeArr  =[NSMutableArray array];
    _requsetUrlSegment = [NSString stringWithFormat:@"%@%@", self.programaUrl, MEIJIA_SHADULE];
    seledayArr =[NSMutableArray array];
    //    NSArray *items = @[@"一对一",@"班级"];
    //    UILabel *titleLb = [[UILabel alloc] init];
    //    titleLb.text = @"课程表";
    
    /**
     http://192.168.6.94:8080/qcbl_edus_auto/dataPlAdd_interfaceShowDateCourse.do?mainId=5083&tableId=17730&minDate=2017-03-06&maxDate=2017-03-08
     
     tableId 固定为传17730
     
     mainId依旧为学员的id
     
     minDate 月初第一天
     
     maxDate  月末  最后一天
     
     接口获取结果中：
     
     
     
     "COURSE_CONTENT": "课程_雅思一对一,课程分类_课程,课程分类ID_1294",
     
     课程分类ID_1294  即为课程类型    分为助教课程  等等
     
     {
     
     "CONFLICT_CONTENT": "课程_雅思一对一,学员:测试学员006,教师_一对一教师003",
     
     "DATA_ID": 61722,
     
     "END_TIME": 1488943800000,
     
     "IFSEE": 1,
     
     "MAIN_DATA_ID": 5083,
     
     "SHOW_CONTENT": "课程_雅思一对一,学员:测试学员006,教师_一对一教师003",
     
     "START_TIME": 1488936600000,
     
     "TABLE_ID": 9547
     
     },
     
     {
     
     "CONFLICT_CONTENT": "课程_雅思一对一,学员:测试学员006,教师_一对一教师003",
     
     "COURSE_CONTENT": "课程_雅思一对一,课程分类_课程,课程分类ID_1294",
     
     "DATA_ID": 61725,
     
     "END_TIME": 1489039200000,
     
     "IFSEE": 1,
     
     "MAIN_DATA_ID": 5083,
     
     "SHOW_CONTENT": "课程_雅思一对一,学员:测试学员006,教师_一对一教师003",
     
     "START_TIME": 1489032000000,
     
     "TABLE_ID": 9547
     
     }**/
    _calanderscheduleArr =[NSMutableArray array];
    _data1 =[NSMutableArray array];
    _data2 =[NSMutableArray array];
    _data3 =[NSMutableArray array];
    
    navBarBtnBottom =[[UIView alloc]initWithFrame:CGRectMake(KWIDTH/2-90/2, 2.5, 90, 35)];
    navBarBtnBottom.backgroundColor =[UIColor whiteColor];
    navBarBtnBottom.layer.cornerRadius = 17;
    
    [self.navigationController.navigationBar addSubview:navBarBtnBottom];
    navBarBtnBottom.hidden = YES;
    
    btn1 =[[UIButton alloc]initWithFrame:CGRectMake(KWIDTH/2-85/2, 5, 80, 30)];
    [btn1 setBackgroundColor:[UIColor clearColor]];
    
    btn2 =[[UIButton alloc]initWithFrame:CGRectMake(KWIDTH/2+5, 5, 80, 30)];
    [btn2 setBackgroundColor:[UIColor clearColor]];
    
    [btn1 setTitle:@"我的课表" forState:UIControlStateNormal];
    [btn2 setTitle:@"班型课程" forState:UIControlStateNormal];
    
    [btn1 setTitleColor:[UIColor redColor] forState:UIControlStateNormal];
    [btn2 setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    
    btn2.titleLabel.font =[UIFont systemFontOfSize:18];
    btn1.titleLabel.font =[UIFont systemFontOfSize:18];
    
    [btn1 addTarget:self action:@selector(btn1Click:) forControlEvents:UIControlEventTouchUpInside];
    [btn2 addTarget:self action:@selector(btn2Click:) forControlEvents:UIControlEventTouchUpInside];
    
    [self createRightNavBar];
    calanderView =[[UIView alloc]init];
    [self.view addSubview:calanderView];
    [calanderView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(self.view.mas_left);
        make.right.equalTo(self.view.mas_right);
        make.top.equalTo(self.view.mas_top).offset(-40);
        make.bottom.equalTo(self.view.mas_bottom);
        
    }];
    
    btn1.hidden = YES;
    btn2.hidden  = YES;
    
    //    segment = [[TNCustomSegment alloc] initWithItems:items withFrame:CGRectMake(KWIDTH/2-50, 5, 100, 30) withSelectedColor:nil withNormolColor:nil withFont:nil];
    //    segment.delegate = self;
    //    segment.selectedIndex = 1;//第一个选择的
    
    [self.navigationController.navigationBar addSubview:btn1];
    
    //*** 暂时 先屏蔽 因为不知道有没有切换的机制
    //    [self.navigationController.navigationBar addSubview:btn2];
    
    //    [self setTitleLabelText:@"课程表"];
    //    titleLb.textAlignment = NSTextAlignmentCenter;
    //    titleLb.font = [UIFont systemFontOfSize:18];
    if (!_pickDate) {
        NSDate *date = [[NSDate alloc] initWithTimeIntervalSinceNow:0];
        [self AmethodForSavePickDate:date];
        
        _pickDateBefore = _pickDate;
        _pickDateBeforeString = _pickDateString;
        
        _returnNowDate = _pickDate;
        _returnNowDateString = _pickDateString;
        
    }
    
    _subViewArr =[[NSMutableArray alloc]init];
    
    _stateDic = @{@"已培训":@"完",@"已预约":@"预"};
    
    
    if (_isHadTabbar == YES) {
        _timeTableSV =[[UIScrollView alloc]initWithFrame:CGRectMake(0, 0, KWIDTH, KHEIGHT-49)];
    }else{
        _timeTableSV =[[UIScrollView alloc]initWithFrame:CGRectMake(0, 0, KWIDTH, KHEIGHT)];
    }
    
    
    
    [self.view addSubview:_timeTableSV];
    
    
    
    
    //
    if(KWIDTH<375){
        _timeTableSV.contentSize = CGSizeMake(KWIDTH, scorllViewCONheight);
    }else{
        _timeTableSV.contentSize = CGSizeMake(KWIDTH, scorllViewCONheight);
    }
    _timeTableSV.backgroundColor =[UIColor whiteColor];
    
    
    
    NSLog(@"+++%f+++",KHEIGHT+210);
    
    _calanderViewBg =[[UIView alloc]initWithFrame:CGRectMake(0, 0, KWIDTH, CALENDER_VIEW_HEIGHT-25)];
    [self.view addSubview:_calanderViewBg];
    [_calanderViewBg addSubview:self.calendarView];
    _calanderViewBg.backgroundColor =[UIColor colorWithHex:0xf5f5f5];
    //    [_timeTableSV addSubview:self.calendarView];
    
    //    _courseListSV =[[UITableView alloc]initWithFrame:CGRectMake(0, 30, KWIDTH, KHEIGHT)];
    _courseListSV = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, KWIDTH, KHEIGHT-130) style:UITableViewStylePlain];
    
    [self.view addSubview:_courseListSV];
    //    _courseListSV.contentSize = CGSizeMake(KWIDTH, KHEIGHT+200);
    
    _monthLable =[[UILabel alloc]initWithFrame:CGRectMake(10, 13, 20, 20)];
    _monthLable.text = @"12";
    _monthLable.font =[UIFont systemFontOfSize:13];
    [self.view addSubview:_monthLable];
    _monthLable.textColor = [UIColor colorWithHex:seleColor];
    
    UILabel *monthText =[[UILabel alloc]initWithFrame:CGRectMake(10, 33, 20, 20)];
    monthText.text = @"月";
    monthText.font =[UIFont systemFontOfSize:13];
    [self.view addSubview:monthText];
    monthText.textColor = [UIColor colorWithHex:seleColor];
    
    _courseListSV.backgroundColor =[UIColor whiteColor];
    
    _courseListSV.hidden = YES;
    _courseListSV.delegate = self;
    _courseListSV.dataSource = self;
    
    UIButton *monthBtn = [[UIButton alloc] init];
    [self.view addSubview:monthBtn];
    monthBtn.backgroundColor = [UIColor clearColor];
    [monthBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(_monthLable.mas_top);
        make.left.equalTo(_monthLable.mas_left);
        make.right.equalTo(monthText.mas_right);
        make.bottom.equalTo(monthText.mas_bottom);
        
    }];
    [monthBtn setTitle:@"" forState:UIControlStateNormal];
    
    [monthBtn addTarget:self action:@selector(btnClick:) forControlEvents:UIControlEventTouchUpInside];
    
    [self drawLine];
    
    //*** she zhi qi dian zhong dian
    [self setStartDateStr];
    [self setEndDateStr];
    
    //    [self setData];
    
    if(self.fromPop){
        [self createLeftNavBar];
    }
    
    _backgroundView = [[UIView alloc] init];
    [self.view addSubview:_backgroundView];
    [_backgroundView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.equalTo(self.view);
    }];
    _backgroundView.backgroundColor = [UIColor colorWithRed:0 green:0 blue:0 alpha:0.5];
    _backgroundView.hidden = YES;
    _backgroundView.tag = 12139;
    [self.view bringSubviewToFront:calanderView];
    //    calanderView.hidden = YES;
    calanderView.backgroundColor =[UIColor colorWithHex:0xf4f4f4];
    [self creatCalander];
    NSDate *date =[NSDate date];
    [self setStartAndEndWithMonth:date];//获取一个月的
    //     [self setTodayAndEndWithMonth:date];//获取一个月的
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(month:) name:@"nowMonth" object:nil];
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(selectDay:) name:@"selectDay" object:nil];
    _ifBtn1 = YES;
    //    [self dataRequest3];
    
    if(isNew==YES){
        
        btn1.hidden = YES;
        btn2.hidden = YES;
        calanderView.hidden = YES;
        navBarBtnBottom.hidden = YES;
    }
    
}

//回到今天课表
//- (void)returnBtnClick:(UIButton *)sender{
//
//    [calendar setCurrentDate:[NSDate date]];
//    //    [self dataRequest3];
//    [self setStartAndEndWithMonth:_returnNowDate];
//}

-(void)selectDay:(NSNotification *)n{
    NSDate * date = [n object];
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    [dateFormatter setDateFormat:@"yyyy-MM-dd"];
    NSString *strDate = [dateFormatter stringFromDate:date];
    _headViewLabel.text = [NSString stringWithFormat:@"%@课程表",strDate];
    [seledayArr removeAllObjects];
    //    searchStart = strDate;
    //    searchEnd = strDate;
    _ifSeleDay=YES;
    //    [self dataRequest2];
    for(ScheduleModel *model in _calanderscheduleArr){
        NSString *str = model.DATE;
        NSArray *arr =[str componentsSeparatedByString:@" "];
        if([arr[0] isEqualToString:strDate]){
            [seledayArr addObject:model];
        }
    }
    NSLog(@"%@",seledayArr);
    [tbView reloadData];
}

-(void)todayArr{
    NSDate *date =[NSDate date];
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    [dateFormatter setDateFormat:@"yyyy-MM-dd"];
    NSString *strDate = [dateFormatter stringFromDate:date];
    [seledayArr removeAllObjects];
    for(ScheduleModel *model in _calanderscheduleArr){
        NSString *str = model.DATE;
        NSArray *arr =[str componentsSeparatedByString:@" "];
        if([arr[0] isEqualToString:strDate]){
            [seledayArr addObject:model];
        }
    }
    
}

-(void)month:(NSNotification *)n{
    NSString * nowMonth = [n object];
    NSArray * now1 = [nowMonth componentsSeparatedByString:@"-"];
    NSString *ss = [NSString stringWithFormat:@"%@-%@",now1[0],now1[1]];
    NSString *str = [NSString stringWithFormat:@"%@-01",ss];
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    [dateFormatter setDateFormat:@"yyyy-MM-dd"];
    NSDate *date = [dateFormatter dateFromString:str];
    if(_ifSeleDay){
        //        [self setStartAndEndWithMonth:date];
        //         [self dataRequest3];
    }else{
        [self setStartAndEndWithMonth:date];
        if(_ifBtn1){
            [self dataRequest3];
        }else{
            [self dataRequest2];
        }
        
    }
    _ifSeleDay = NO;
    
}

- (void)createRightNavBar{
    
    //    UIButton *rightNavBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    //    self.leftBtn = leftNavBtn;
    
    //    [rightNavBtn setTitle:@"回到当月" forState:UIControlStateNormal];
    //    rightNavBtn.frame = CGRectMake(0, 0, 60, 20);
    //    rightNavBtn.titleLabel.font = [UIFont systemFontOfSize:20];
    //    [rightNavBtn addTarget:self action:@selector(returnBtnClick:) forControlEvents:UIControlEventTouchUpInside];
    //    UIBarButtonItem *item = [[UIBarButtonItem alloc]initWithCustomView:rightNavBtn];
    //    self.navigationItem.rightBarButtonItem = item;
    
    UIButton *rightNavBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    rightNavBtn.frame = CGRectMake(0, 0, 44/2, 44/2);
    //    [rightNavBtn setBackgroundImage:[UIImage imageNamed:@"形状1-19-拷贝-4"] forState:UIControlStateNormal];
    [rightNavBtn setTitle:@"" forState:UIControlStateNormal];
    
    [rightNavBtn setImage:[UIImage imageNamed:@"jintian"] forState:UIControlStateNormal];
    
    [rightNavBtn addTarget:self action:@selector(returnBtnClick:) forControlEvents:UIControlEventTouchUpInside];
    UIBarButtonItem *item = [[UIBarButtonItem alloc]initWithCustomView:rightNavBtn];
    self.navigationItem.rightBarButtonItem = item;
    
}

//获取当天的日期
-(void)setTodayAndEndWithMonth:(NSDate *)day{
    
    NSDateFormatter *dateFormatter=[[NSDateFormatter alloc]init];//创建一个日期格式化器
    
    dateFormatter.dateFormat=@"yyyy-MM-dd";//指定转date得日期格式化形式
    
    NSArray *arr = [[dateFormatter stringFromDate:day]componentsSeparatedByString:@"-"];
    if(_ifSeleDay){
        
    }else{
        searchStart = [NSString stringWithFormat:@"%@-%@-%@",arr[0],arr[1],arr[2]];
        searchEnd = [NSString stringWithFormat:@"%@-%@-%@",arr[0],arr[1],arr[2]];
        _headViewLabel.text = [NSString stringWithFormat:@"%@到%@课程表",searchStart,searchEnd];
    }
    
    
}


-(void)setStartAndEndWithMonth:(NSDate *)day{
    
    NSDateFormatter *dateFormatter=[[NSDateFormatter alloc]init];//创建一个日期格式化器
    
    dateFormatter.dateFormat=@"yyyy-MM-dd";//指定转date得日期格式化形式
    
    NSArray *arr = [[dateFormatter stringFromDate:day]componentsSeparatedByString:@"-"];
    
    NSString *strDate = [dateFormatter stringFromDate:day];
    NSInteger lastDay = [self howManyDaysInThisYear:[arr[0] integerValue] withMonth:[arr[1] integerValue]];
    if(_ifSeleDay){
        
    }else{
        searchStart = [NSString stringWithFormat:@"%@-%@-%@",arr[0],arr[1],@"01"];
        searchEnd = [NSString stringWithFormat:@"%@-%@-%ld",arr[0],arr[1],(long)lastDay];
        //        _headViewLabel.text = [NSString stringWithFormat:@"%@到%@课程表",searchStart,searchEnd];
        _headViewLabel.text = [NSString stringWithFormat:@"%@课程表",strDate];
    }
    
    
}

- (NSInteger)howManyDaysInThisYear:(NSInteger)year withMonth:(NSInteger)month{
    if((month == 1) || (month == 3) || (month == 5) || (month == 7) || (month == 8) || (month == 10) || (month == 12))
        return 31 ;
    
    if((month == 4) || (month == 6) || (month == 9) || (month == 11))
        return 30;
    
    if((year % 4 == 1) || (year % 4 == 2) || (year % 4 == 3))
    {
        return 28;
    }
    
    if(year % 400 == 0)
        return 29;
    
    if(year % 100 == 0)
        return 28;
    
    return 29;
}

-(void)searchCondition{
    
    NSMutableDictionary *parama = [[NSMutableDictionary alloc]init];
    
    
    [parama setObject:[NSString stringWithFormat:@"%@", userId()] forKey:@"mainId"];
    
    NSString * requestStr = [NSString stringWithFormat:@"%@%@", self.programaUrl, SHANGYUAN_SEARCH];
    
    [NetRequest requestUrl:requestStr andParamas:parama andReturnBlock:^(NSData *data, NSError *error) {
        if (!error&&data!=nil) {
            id obj = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
            NSLog(@"%@", obj);
            
            
            if ([obj valueForKey: @"promptMessage"]) {
                [[NSNotificationCenter defaultCenter]postNotificationName:@"relogin" object:@"relogin"];
                return ;
            }
            //            _data1 = [NSMutableArray arrayWithObjects:@"智能排序", @"离我最近", @"评价最高", @"最新发布", @"人气最高", @"价格最低", @"价格最高", nil];
            [_data1 removeAllObjects];
            
            _searchArr =[NSMutableArray arrayWithArray:[obj objectForKey:@"dataInfo"]];
            
            for(NSDictionary *dic in _searchArr){
                [_data1 addObject:[dic objectForKey:@"CT_NAME"]];
            }
            if(_searchArr.count!=0){
                _CT_ID =[NSString stringWithFormat:@"%@",[_searchArr[0]objectForKey:@"CLASS_TYPE_ID"]];
            }
            _NOW_BOUT = @"1";
            _CM_TYPE = @"";
            NSUInteger ke_ci = 0;
            if(_searchArr.count!=0){
                ke_ci = [[[_searchArr objectAtIndex:0]objectForKey:@"ALL_BOUT"] integerValue];
                [_data2 removeAllObjects];
                for(int i=0;i<ke_ci;i++){
                    [_data2 addObject:[NSString stringWithFormat:@"第%d次课",i+1]];
                }
            }
            
            
            
            _data3 = [NSMutableArray arrayWithObjects:@"更多筛选", @"离我最近", @"评价最高", @"最新发布", @"人气最高", @"价格最低", @"价格最高", nil];
            menu = [[JSDropDownMenu alloc] initWithOrigin:CGPointMake(0, 0) andHeight:45];
            menu.indicatorColor = [UIColor colorWithRed:175.0f/255.0f green:175.0f/255.0f blue:175.0f/255.0f alpha:1.0];
            menu.separatorColor = [UIColor colorWithRed:210.0f/255.0f green:210.0f/255.0f blue:210.0f/255.0f alpha:1.0];
            menu.textColor = [UIColor colorWithRed:83.f/255.0f green:83.f/255.0f blue:83.f/255.0f alpha:1.0f];
            menu.dataSource = self;
            menu.delegate = self;
            menu.obj = self;
            menu.endButton = @selector(endSearch);
            menu.satrtButton = @selector(startSearch);
            menu.typeBtnSelecter = @selector(typeBtnClick:);
            menu.set_sel = @selector(setSearch);
            menu.back_sel = @selector(backClick);
            [calanderView addSubview:menu];
            [self dataRequest3];
            
        }else{
            NSString *string = [NSString stringWithFormat:@"%@", error.localizedDescription];
            [self showLabelWithText:string];
        }
    }];
    
}


-(void)setSearch{
    
    [self dataRequest2];
}

-(void)backClick{
    
}

-(void)typeBtnClick:(UIButton *)btn{
    NSLog(@"btn---tag%ld",(long)btn.tag);
    if(btn.tag!=300){
        _CM_TYPE=[NSString stringWithFormat:@"%ld",(long)btn.tag];
    }else{
        _CM_TYPE=@"";
    }
}

-(void)endSearch{
    NSLog(@"wer");
    [dater showInView:self.view animated:YES];
    _isStart=NO;
    
}


-(void)daterViewDidClicked:(XFDaterView *)daterView{//点中选择器选择控件
    NSString *str = [NSString stringWithFormat:@"%d-%02d-%02d",daterView.year,daterView.month,daterView.day];
    NSLog(@"%d-%d-%d",daterView.year,daterView.month,daterView.day);
    if(_isStart){
        [menu.btnStart setTitle:str forState:UIControlStateNormal];
        searchStart = str;
    }else{
        [menu.btnend setTitle:str forState:UIControlStateNormal];
        searchEnd = str;
    }
}

-(void)startSearch{
    _isStart=YES;
    NSLog(@"ddwer");
    [dater showInView:self.view animated:YES];
}

-(void)creatCalander{
    
    //    calendar = [[FDCalendar alloc] initWithCurrentDate:[NSDate date]];
    //    CGRect frame = calendar.frame;
    //    frame.origin.y = 0;
    //    calendar.frame = frame;
    //    [calanderView addSubview:calendar];
    //    calendar.obj = self;
    //    calendar.seleDayButton = @selector(seleBtnClick);
    //    self.view.backgroundColor =[UIColor colorWithRed:244.0/255.0 green:244.0/255.0 blue:244.0/255.0 alpha:1];
    
    
    tbView =[[UITableView alloc]initWithFrame:CGRectMake(0, 52, [UIScreen mainScreen].bounds.size.width, [UIScreen mainScreen].bounds.size.height-60-70) style:UITableViewStylePlain];
    tbView.backgroundColor =[UIColor clearColor];
    [calanderView addSubview:tbView];
    tbView.dataSource = self;
    tbView.separatorStyle = UITableViewCellSeparatorStyleNone;
    tbView.delegate = self;
    
    UIView *headView =[[UIView alloc]initWithFrame:CGRectMake(0, 0, [UIScreen mainScreen].bounds.size.width, 338)];
    headView.backgroundColor =[UIColor clearColor];
    
    calendar = [[FDCalendar alloc] initWithCurrentDate:[NSDate date]];
    CGRect frame = calendar.frame;
    frame.origin.y = -45;
    calendar.frame = frame;
    [headView addSubview:calendar];
    calendar.obj = self;
    calendar.seleDayButton = @selector(seleBtnClick);
    self.view.backgroundColor =[UIColor colorWithRed:244.0/255.0 green:244.0/255.0 blue:244.0/255.0 alpha:1];
    
    UIView *vv =[[UIView alloc]initWithFrame:CGRectMake(0, 295, KWIDTH, 42)];
    [headView addSubview:vv];
    vv.backgroundColor =[UIColor whiteColor];
    
    UIImageView *img =[[UIImageView alloc]initWithFrame:CGRectMake(17, 13.5, 15, 15)];
    [vv addSubview:img];
    img.image =[UIImage imageNamed:@"cur_curriculum"];
    
    _headViewLabel = [[UILabel alloc]initWithFrame:CGRectMake(40, 13.5-2, 250, 20)];
    [vv addSubview:_headViewLabel];
    _headViewLabel.text = [NSString stringWithFormat:@"%@到%@课程表",searchStart,searchEnd];
    _headViewLabel.font =[UIFont systemFontOfSize:16];
    _headViewLabel.textColor = [UIColor colorWithHex:0x4c4c4c];
    
    UIView *lineV =[[UIView alloc]init];
    [headView addSubview:lineV];
    [lineV mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(_headViewLabel.mas_bottom).offset(15);
        make.left.equalTo(headView.mas_left);
        make.right.equalTo(headView.mas_right);
        make.height.equalTo(@(0.5));
    }];
    
    tbView.tableHeaderView = headView; //添加在这里随table滚动而滚动
    
    dater=[[XFDaterView alloc]initWithFrame:CGRectZero];
    dater.delegate=self;
    
    
    _searchBarView = [[UIView alloc]init];
    [calanderView addSubview:_searchBarView];
    [_searchBarView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(calanderView.mas_left);
        make.right.equalTo(calanderView.mas_right);
        make.top.equalTo(calanderView.mas_top);
        make.height.equalTo(@(45));
    }];
    _searchBarView.backgroundColor =[UIColor whiteColor];
    
    // 指定默认选中
    _currentData1Index = 0;//默认选中第一个
    _currentData1SelectedIndex = 0;
    
    //    _data1 = [NSMutableArray arrayWithObjects:@"智能排序", @"离我最近", @"评价最高", @"最新发布", @"人气最高", @"价格最低", @"价格最高", nil];
    //
    //    _data2 = [NSMutableArray arrayWithObjects:@"智能排序", @"离我最近", @"评价最高", @"最新发布", @"人气最高", @"价格最低", @"价格最高", nil];
    //    _data3 = [NSMutableArray arrayWithObjects:@"智能排序", @"离我最近", @"评价最高", @"最新发布", @"人气最高", @"价格最低", @"价格最高", nil];
    tbView.header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        [self loadNewData];
    }];
    
    tbView.footer = [MJRefreshAutoNormalFooter footerWithRefreshingBlock:^{
        [self footerRefresh];
    }];
    
    
}


#pragma mark - Refresh
-(void)loadNewData{
    
    
    
    [tbView.header beginRefreshing];
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(MJDuration * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        
        //*** setting edit style
        
        
        
        // 刷新表格
        [[NSNotificationCenter defaultCenter]postNotificationName:@"refresh" object:@"dd"];
        [self dataRequest3];
        
        _ifSeleDay = NO;
        
        // 拿到当前的下拉刷新控件，结束刷新状态
        [tbView.header endRefreshing];
    });
    
}

#pragma mark - Refresh
-(void)footerRefresh{
    [tbView.footer beginRefreshing];
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(MJDuration * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        
        
        // 拿到当前的下拉刷新控件，结束刷新状态
        [tbView.footer endRefreshing];
    });
    
}

- (NSInteger)numberOfColumnsInMenu:(JSDropDownMenu *)menu {
    
    return 3;
}

-(BOOL)displayByCollectionViewInColumn:(NSInteger)column{
    
    //    if (column==2) {
    //
    //        return YES;
    //    }
    
    return NO;
}

-(BOOL)haveRightTableViewInColumn:(NSInteger)column{
    
    //    if (column==0) {
    //        return YES;
    //    }
    return NO;
}

-(CGFloat)widthRatioOfLeftColumn:(NSInteger)column{//宽度
    
    if (column==0) {
        return 1;
    }
    
    return 1;
}

-(NSInteger)currentLeftSelectedRow:(NSInteger)column{
    
    if (column==0) {
        
        return _currentData1Index;
        
    }
    if (column==1) {
        
        return _currentData2Index;
    }
    if (column==2) {
        
        return _currentData3Index;
    }
    return 0;
}

- (NSInteger)menu:(JSDropDownMenu *)menu numberOfRowsInColumn:(NSInteger)column leftOrRight:(NSInteger)leftOrRight leftRow:(NSInteger)leftRow{
    
    //    if (column==0) {
    //        if (leftOrRight==0) {
    //
    //            return _data1.count;
    //        } else{
    //
    //            NSDictionary *menuDic = [_data1 objectAtIndex:leftRow];
    //            return [[menuDic objectForKey:@"data"] count];
    //        }
    //    } else if (column==1){
    //
    //        return _data2.count;
    //
    //    } else if (column==2){
    //
    //        return _data3.count;
    //    }
    NSLog(@"%ld",(long)column);
    if(column==0){
        return _data1.count;
    }else if (column==1){
        return _data2.count;
    }else if (column==2){
        return _data3.count;
    }
    
    return 0;
}
//搜索部分显示的标题
- (NSString *)menu:(JSDropDownMenu *)menu titleForColumn:(NSInteger)column{
    
    //    switch (column) {
    //        case 0: return [[_data1[_currentData1Index] objectForKey:@"data"] objectAtIndex:_currentData1SelectedIndex];
    //            break;
    //        case 1: return _data2[_currentData2Index];
    //            break;
    //        case 2: return _data3[_currentData3Index];
    //            break;
    //        default:
    //            return nil;
    //            break;
    //    }
    switch (column) {
        case 0: if(_data1.count>0){
            return _data1[_currentData1Index];
        }else{
            return @"无条件";
        }
            break;
        case 1:if(_data2.count>0){
            return _data2[_currentData2Index];
        }else{
            return @"无条件";
        }
            
            break;
            
        case 2:if(_data3.count>0){
            return _data3[_currentData3Index];
        }else{
            return nil;
        }
            
            break;
        default:
            return nil;
            break;
    }
    
}

- (NSString *)menu:(JSDropDownMenu *)menu titleForRowAtIndexPath:(JSIndexPath *)indexPath {
    
    if (indexPath.column==0) {
        //        if (indexPath.leftOrRight==0) {
        //            NSDictionary *menuDic = [_data1 objectAtIndex:indexPath.row];
        //            return [menuDic objectForKey:@"title"];
        //        } else{
        //            NSInteger leftRow = indexPath.leftRow;
        //            NSDictionary *menuDic = [_data1 objectAtIndex:leftRow];
        //            return [[menuDic objectForKey:@"data"] objectAtIndex:indexPath.row];
        //        }
        return _data1[indexPath.row];
    } else if (indexPath.column==1) {
        
        return _data2[indexPath.row];
        
    } else {
        
        return _data3[indexPath.row];
    }
}

- (void)menu:(JSDropDownMenu *)menu didSelectRowAtIndexPath:(JSIndexPath *)indexPath {
    
    if (indexPath.column == 0) {
        
        //        if(indexPath.leftOrRight==0){
        //
        //            _currentData1Index = indexPath.row;
        //
        //            return;
        //        }
        NSUInteger ke_ci = [[[_searchArr objectAtIndex:indexPath.row]objectForKey:@"ALL_BOUT"] integerValue];
        NSDictionary *dic = [_searchArr objectAtIndex:indexPath.row];
        [_data2 removeAllObjects];
        for(int i=0;i<ke_ci;i++){
            [_data2 addObject:[NSString stringWithFormat:@"第%d次课",i+1]];
        }
        _currentData1Index = indexPath.row;
        _ifseleData1 = YES;
        _CT_ID = [NSString stringWithFormat:@"%@",[dic objectForKey:@"CLASS_TYPE_ID"]];
        
    } else if(indexPath.column == 1){
        
        _currentData2Index = indexPath.row;
        _NOW_BOUT = [NSString stringWithFormat:@"%ld",(long)indexPath.row+1];
        
    } else{
        
        _currentData3Index = indexPath.row;
    }
    [self dataRequest2];
}

//班课日历请求
-(void)dataRequest2{
    NSMutableDictionary *parama = [[NSMutableDictionary alloc]init];
    if([getUIStyle() isEqualToString:STYLE0]){
        //
        //        [parama setObject:tableIdStr forKey:@"tableId"];
#pragma mark - 放开课程表
        [parama setObject:@"2" forKey:@"tableId"];
    }else{
        //#elif Student
        [parama setObject:@"19" forKey:@"tableId"];
    }
    //#else
    
    //#endif
    
    
    
    [parama setObject:[NSString stringWithFormat:@"%@", userId()] forKey:@"mainId"];
    
    [parama setObject:[NSString stringWithFormat:@"%@", searchStart] forKey:@"minDate"];
    [parama setObject:[NSString stringWithFormat:@"%@", searchEnd] forKey:@"maxDate"];
    
    if(!_ifBtn1){
        if(_CT_ID==nil){
            [parama setObject:@"" forKey:@"CT_ID"];
            [parama setObject:@"" forKey:@"NOW_BOUT"];
            [parama setObject:@"" forKey:@"CM_TYPE"];
        }else{
            [parama setObject:_CT_ID forKey:@"CT_ID"];
            [parama setObject:_NOW_BOUT forKey:@"NOW_BOUT"];
            [parama setObject:_CM_TYPE forKey:@"CM_TYPE"];
        }
        
    }
    
    /*----  当滑动过后相当于pick日期，也需要将pick的日期修改，周为单位只需修改为这一周的任意一天就可以  ----*/
    //    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    //    [dateFormatter setDateFormat:@"yyyy-MM-dd"];
    //    _pickDateBefore = [dateFormatter dateFromString:_startDateStr];
    //    _pickDateBeforeString = _startDateStr;
    
    NSString *requestStr;
    
    if([getUserType() isEqualToString:STYLE0]){
        
        requestStr = [NSString stringWithFormat:@"%@%@", self.programaUrl, SHANGYUAN_SHADULE];
    }else{
        if(_ifBtn1){
            requestStr = [NSString stringWithFormat:@"%@%@", self.programaUrl, KECHENGBIAO_URl];//上元学员修改
        }else{
            requestStr = [NSString stringWithFormat:@"%@%@", self.programaUrl, SHANGYUAN_SHADULE];//上元学员修改
        }
        
    }
    
    
    
    [NetRequest requestUrl:requestStr andParamas:parama andReturnBlock:^(NSData *data, NSError *error) {
        if (!error&&data!=nil) {
            id obj = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
            
            if ([obj valueForKey: @"promptMessage"]) {
                [[NSNotificationCenter defaultCenter]postNotificationName:@"relogin" object:@"relogin"];
                return ;
            }
            _ifSeleDay = NO;
            NSLog(@"%@", obj);
            NSMutableArray *time2 =[NSMutableArray array];
            NSArray *arr = [obj objectForKey:@"dataInfo"];
            [_calanderscheduleArr removeAllObjects];
            for(NSDictionary *dic in arr){
                ScheduleModel *model =[[ScheduleModel alloc]init];
                model = [model initWithDictionary:dic error:nil];
                [_calanderscheduleArr addObject:model];
                [_timeArr addObject:[self stringToTIme2:model.COURSE_DATE]];
                NSArray *ss =[[self stringToTIme2:model.COURSE_DATE] componentsSeparatedByString:@" "];
                [time2 addObject:ss[0]];
            }
            NSLog(@"%@",_timeArr);
            
            NSMutableDictionary *dict = [NSMutableDictionary dictionary];
            
            for (NSString *str in time2) {
                
                [dict setObject:str forKey:str];
                
            }
            [self todayArr];
            NSArray *array = [dict allKeys];
            [[NSNotificationCenter defaultCenter]postNotificationName:@"time" object:array];
            [tbView reloadData];
        }else{
            NSString *string = [NSString stringWithFormat:@"%@", error.localizedDescription];
            [self showLabelWithText:string];
        }
    }];
}

-(void)dataRequest3{
    NSMutableDictionary *parama = [[NSMutableDictionary alloc]init];
    if([getUIStyle() isEqualToString:STYLE0]){
        //
        //        [parama setObject:tableIdStr forKey:@"tableId"];
#pragma mark - 放开课程表
        [parama setObject:@"106" forKey:@"tableId"];
    }else{
        //#elif Student
        [parama setObject:@"17730" forKey:@"tableId"];
    }
    //#else
    
    //#endif
    
    
    [parama setObject:@"4775" forKey:@"pageId"];
     [parama setObject:@"0" forKey:@"COURSE_DATE_3_andOr"];
     [parama setObject:@"yyyy-MM-dd" forKey:@"COURSE_DATE_dateType"];
//    [parama setObject:[NSString stringWithFormat:@"%@", userId()] forKey:@"mainId"];
    
    [parama setObject:[NSString stringWithFormat:@"%@", searchStart] forKey:@"COURSE_DATE_startDates_pld"];
    [parama setObject:[NSString stringWithFormat:@"%@", searchEnd] forKey:@"COURSE_DATE_endDates_pld"];
    
    
    /*----  当滑动过后相当于pick日期，也需要将pick的日期修改，周为单位只需修改为这一周的任意一天就可以  ----*/
    //    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    //    [dateFormatter setDateFormat:@"yyyy-MM-dd"];
    //    _pickDateBefore = [dateFormatter dateFromString:_startDateStr];
    //    _pickDateBeforeString = _startDateStr;
    
    NSString *requestStr;
    
    if([getUserType() isEqualToString:STYLE0]){
        
        requestStr = [NSString stringWithFormat:@"%@%@", self.programaUrl, PERSONAL_INFO_URl];
    }else{
        
        requestStr = [NSString stringWithFormat:@"%@%@", self.programaUrl, PERSONAL_INFO_URl];//学员修改
        
        
    }
    
    
    
    [NetRequest requestUrl:requestStr andParamas:parama andReturnBlock:^(NSData *data, NSError *error) {
        if (!error&&data!=nil) {
            id obj = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
            
            if ([obj valueForKey: @"promptMessage"]) {
                [[NSNotificationCenter defaultCenter]postNotificationName:@"relogin" object:@"relogin"];
                return ;
            }
            _ifSeleDay = NO;
            NSLog(@"______~~~~~~~hahha%@", obj);
            NSMutableArray *time2 =[NSMutableArray array];
            NSArray *arr = [obj objectForKey:@"dataList"];
            [_calanderscheduleArr removeAllObjects];
            for(NSDictionary *dic in arr){
                ScheduleModel *model =[[ScheduleModel alloc]init];
                model = [model initWithDictionary:dic error:nil];
                [_calanderscheduleArr addObject:model];
                [_timeArr addObject:model.DATE];
                [time2 addObject:model.DATE];
            }
            NSLog(@"%@",_timeArr);
            
            NSMutableDictionary *dict = [NSMutableDictionary dictionary];
            [self todayArr];
            for (NSString *str in time2) {
                
                [dict setObject:str forKey:str];
                
            }
            NSArray *array = [dict allKeys];
            [[NSNotificationCenter defaultCenter]postNotificationName:@"time" object:array];
            [tbView reloadData];
            
            
        }else{
            NSString *string = [NSString stringWithFormat:@"%@", error.localizedDescription];
            [self showLabelWithText:string];
        }
    }];
}

//-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
//    return 40;
//}
//
//- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
//{
//    //添加在这里不随滚动而滚动
//    UIView *headView =[[UIView alloc]initWithFrame:CGRectMake(0, 0, [UIScreen mainScreen].bounds.size.width, 50)];
//    headView.backgroundColor =[UIColor whiteColor];
//
//    UIImageView *img =[[UIImageView alloc]initWithFrame:CGRectMake(17, 15, 15, 15)];
//    [headView addSubview:img];
//    img.image =[UIImage imageNamed:@"cur_curriculum"];
//
//    _headViewLabel = [[UILabel alloc]initWithFrame:CGRectMake(40, 13, 250, 20)];
//    [headView addSubview:_headViewLabel];
//    _headViewLabel.text = [NSString stringWithFormat:@"%@到%@课程表",searchStart,searchEnd];
//    _headViewLabel.font =[UIFont systemFontOfSize:16];
//    _headViewLabel.textColor = [UIColor colorWithHex:0x4c4c4c];
//
//    UIView *lineV =[[UIView alloc]init];
//    [headView addSubview:lineV];
//    [lineV mas_makeConstraints:^(MASConstraintMaker *make) {
//        make.top.equalTo(_headViewLabel.mas_bottom).offset(15);
//        make.left.equalTo(headView.mas_left);
//        make.right.equalTo(headView.mas_right);
//        make.height.equalTo(@(0.5));
//    }];
//    return headView;
//}


-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return 189/2;
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    if(_ifSeleDay&&seledayArr.count>0){
        return seledayArr.count;
        
    }else{
        //        return _calanderscheduleArr.count;
        return seledayArr.count;
    }
    
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    static NSString *str = @"identifier";
    ScheduleCell *cell =[tableView dequeueReusableCellWithIdentifier:str];
    if(cell==nil){
        cell =[[ScheduleCell alloc]initWithidentirier:str];
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        
    }
    ScheduleModel *model =[[ScheduleModel alloc]init];
    if(_ifSeleDay){
        model=[seledayArr objectAtIndex:indexPath.row];
        if(indexPath.row==seledayArr.count-1){
            _ifSeleDay=NO;
        }
        
    }else{
        //        model=[_calanderscheduleArr objectAtIndex:indexPath.row];
        model=[seledayArr objectAtIndex:indexPath.row];
    }
    
    if(model.COURSENAME){
        cell.classNum.text = model.COURSENAME;
    }else{
        cell.classNum.text = @"暂无";
    }
    if(model.START_TIME){
        cell.startTime.text = model.START_TIME;
    }else{
        cell.startTime.text = @"暂无";
    }
    if(model.END_TIME){
        cell.endTime.text = model.END_TIME;
    }else{
        cell.endTime.text = @"暂无";
    }
    if(model.DIC_STATE){
        cell.couresType.text = model.DIC_STATE;
    }else{
        cell.couresType.text = @"暂无";
    }
    if(model.TEACHER){
        cell.teacherName.text = model.TEACHER;
    }else{
       cell.teacherName.text = @"暂无";
    }
   
    return cell;
}

//#pragma mark - 打电话 按钮 点击事件
//-(void)callPhoneBtnClick:(MyButton *)btn{
//    NSLog(@"打电话");
//}
//
//#pragma mark - 发消息 按钮 点击事件
//-(void)messageBtnClick:(MyButton *)btn{
//    NSLog(@"发消息");
//}
-(NSString *)stringToTIme:(NSString *)str{
    long time=[str longLongValue];
    
    NSDate *d = [[NSDate alloc]initWithTimeIntervalSince1970:time/1000.0];
    
    NSDateFormatter *df = [[NSDateFormatter alloc] init];//格式化
    
    [df setDateFormat:@"HH:mm"];
    
    [df setLocale:[[NSLocale alloc] initWithLocaleIdentifier:@"zh_CN"] ];
    
    NSString * timeStr =[df stringFromDate:d];
    
    return timeStr;
}

-(NSString *)stringToTIme2:(NSString *)str{
    long time=[str longLongValue];
    
    NSDate *d = [[NSDate alloc]initWithTimeIntervalSince1970:time/1000.0];
    
    NSDateFormatter *df = [[NSDateFormatter alloc] init];//格式化
    
    [df setDateFormat:@"yyyy-MM-dd HH:mm"];
    
    [df setLocale:[[NSLocale alloc] initWithLocaleIdentifier:@"zh_CN"] ];
    
    NSString * timeStr =[df stringFromDate:d];
    
    return timeStr;
}

#pragma mark - 点击月份弹出选择器（按钮）
- (void)btnClick:(UIButton *)sender
{
    NSLog(@"adkljflaskfdjlsajf");
    _backgroundView.hidden = NO;
    
    //单击手势
    UITapGestureRecognizer *sideslipTapGes= [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(handeTap:)];
    [sideslipTapGes setNumberOfTapsRequired:1];
    
    [_backgroundView addGestureRecognizer:sideslipTapGes];
    sideslipTapGes.cancelsTouchesInView = YES;  //点击事件盖住其它响应事件,但盖不住Button;
    if (!_datePicker) {
        
        UITapGestureRecognizer *tap= [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(handeTap:)];
        [tap setNumberOfTapsRequired:1];
        
        [_testLabel addGestureRecognizer:tap];
        NSDate* date = [[NSDate alloc] initWithTimeIntervalSinceNow:0];
        _datePicker = [[UIDatePicker alloc] initWithFrame:CGRectMake(0.0,0.0,0.0,0.0)];
        _datePicker.backgroundColor = [UIColor whiteColor];
        UIView *pickerBgView = [[UIView alloc] init];
        [self.backgroundView addSubview:pickerBgView];
        pickerBgView.backgroundColor = [UIColor whiteColor];
        [pickerBgView mas_makeConstraints:^(MASConstraintMaker *make) {
            if (_isHadTabbar == YES) {
                make.bottom.equalTo(_backgroundView.mas_bottom).offset(-49);
            }else{
                make.bottom.equalTo(_backgroundView.mas_bottom).offset(0);
            }
            
            make.left.equalTo(_backgroundView.mas_left);
            make.right.equalTo(_backgroundView.mas_right);
            make.height.equalTo(@(426/2));
        }];
        
        _datePicker.datePickerMode = UIDatePickerModeDate;
        [ _datePicker setDate:date animated:YES];
        [pickerBgView addSubview:_datePicker];
        [ _datePicker addTarget:self action:@selector(dateChanged:) forControlEvents:UIControlEventValueChanged];
        [_datePicker mas_makeConstraints:^(MASConstraintMaker *make) {
            make.edges.equalTo(pickerBgView);
        }];
    }
    if (!_btnBackgroundView) {
        _btnBackgroundView = [[UIView alloc] init];
        _btnBackgroundView.backgroundColor = [UIColor whiteColor];
        [_backgroundView addSubview:_btnBackgroundView];
        [_btnBackgroundView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.bottom.equalTo(_datePicker.mas_top);
            make.right.equalTo(_datePicker.mas_right);
            make.left.equalTo(_datePicker.mas_left);
            make.height.equalTo(@(84/2));
        }];
    }
    if (!_saveBtn) {
        _saveBtn = [UIButton buttonWithType:UIButtonTypeCustom];
        [_saveBtn setTitle:@"确定" forState:UIControlStateNormal];
        [_backgroundView addSubview:_saveBtn];
        _saveBtn.userInteractionEnabled = NO;
        [_saveBtn mas_makeConstraints:^(MASConstraintMaker *make) {
            make.top.equalTo(_btnBackgroundView.mas_top);
            make.bottom.equalTo(_btnBackgroundView.mas_bottom);
            make.right.equalTo(_btnBackgroundView.mas_right).offset(-36/2);
            make.width.equalTo(@(50));
        }];
        _saveBtn.titleLabel.font = [UIFont systemFontOfSize:32/2];
        [_saveBtn setBackgroundColor:[UIColor whiteColor]];
        [_saveBtn setTitleColor:[UIColor colorWithHex:0x4ca5ff] forState:UIControlStateNormal];
        [_saveBtn addTarget:self action:@selector(pickBtnClick:) forControlEvents:UIControlEventTouchUpInside];
    }
    if (!_cancelBtn) {
        _cancelBtn = [UIButton buttonWithType:UIButtonTypeCustom];
        [_cancelBtn setTitle:@"取消" forState:UIControlStateNormal];
        [_backgroundView addSubview:_cancelBtn];
        [_cancelBtn mas_makeConstraints:^(MASConstraintMaker *make) {
            make.centerY.equalTo(_btnBackgroundView.mas_centerY);
            make.left.equalTo(_btnBackgroundView.mas_left).offset(36/2);
            make.width.equalTo(@(50));
        }];
        [_cancelBtn setBackgroundColor:[UIColor whiteColor]];
        _cancelBtn.titleLabel.font = [UIFont systemFontOfSize:32/2];
        [_cancelBtn setTitleColor:[UIColor colorWithHex:0x858585] forState:UIControlStateNormal];
        [_cancelBtn addTarget:self action:@selector(cancelBtnClick:) forControlEvents:UIControlEventTouchUpInside];
    }
    if (!_lineView) {
        _lineView = [[UIView alloc] init];
        [_btnBackgroundView addSubview:_lineView];
        [_lineView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.top.equalTo(_btnBackgroundView.mas_bottom);
            make.left.equalTo(_btnBackgroundView.mas_left);
            make.right.equalTo(_btnBackgroundView.mas_right);
            make.height.equalTo(@(1));
        }];
        _lineView.backgroundColor = [UIColor colorWithHex:0xe3e3e3];
    }
    UITapGestureRecognizer *sideslipTapGesView= [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(handeTapView:)];
    [sideslipTapGesView setNumberOfTapsRequired:1];
    
    [_btnBackgroundView addGestureRecognizer:sideslipTapGesView];
    
    sideslipTapGesView.cancelsTouchesInView = YES;
    _btnBackgroundView.userInteractionEnabled = YES;
    _btnBackgroundView.tag = 12138;
}

#pragma mark - 当日期选择器显示后点击空白地方调用的方法（取消选择操作）
- (void)handeTap:(UITapGestureRecognizer *)sender{
    UIView *targetview = sender.view;
    NSLog(@"%ld",targetview.tag);
    if (targetview.tag == 12139) {
        if (sender.state == UIGestureRecognizerStateEnded) {
            NSLog(@"单击时间");
        }
        NSLog(@"单击几次%ld",sender.numberOfTouches);
        _backgroundView.hidden = YES;
    }else{
        
    }
}
- (void)handeTapView:(UITapGestureRecognizer *)sender{
    UIView *targetView = sender.view;
    NSLog(@"%ld",targetView.tag);
    if (targetView.tag == 12138) {
        _backgroundView.hidden = YES;
    }
}

#pragma mark - 选择器选择日期完成后调用
-(void)dateChanged:(id)sender{
    _saveBtn.userInteractionEnabled = YES;
    //    UIDatePicker* control = (UIDatePicker*)sender;
    //    NSDate* _date = control.date;
    //    NSDateFormatter *df = [[NSDateFormatter alloc] init];
    //    [df setDateFormat:@"yyyy-MM-dd"];
    //    NSString *str = [df stringFromDate:_date];
    //    _pickDate = _date;
    //    _pickDateString = str;
    //
    //    /*添加你自己响应代码*/
    //    NSLog(@"+++++str:“%@”++++",str);
}

#pragma mark - 确定按钮（触发变更日期）
- (void)pickBtnClick:(UIButton *)sender{
    NSLog(@"%@",_datePicker.date);
    NSLog(@"确定");
    NSLog(@"%@%@",_pickDate,_pickDateString);
    _pickDateBeforeString = _pickDateString;
    _pickDateBefore = _pickDate;
    
    [self AmethodForSavePickDate:_datePicker.date];
    
    
    NSArray * myGetDate = [self getStartDateAndEndDate:_pickDate];
    NSArray * myGetDateBefore = [self getStartDateAndEndDate:_pickDateBefore];
    
    NSLog(@"---+++--->%@<---+++--->%@<---+++---",myGetDate,myGetDateBefore);
    
    
    
    
    // 在当前日期(去掉时分秒)基础上加上差的天数
    
    
    
    BOOL blnToday = NO;
    BOOL SwipeWay;
    
    
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    [formatter setDateFormat:@"yyyy-MM-dd"];
    
    _startDateStr = [self DateBecomeString:[myGetDate firstObject]];
    _endDateStr = [self DateBecomeString:[myGetDate lastObject]];
    
    _calendarView.startDate =[myGetDate firstObject];
    _calendarView.endDate =[myGetDate lastObject];
    NSLog(@"%d",[[self DateBecomeString:[myGetDate firstObject]]isEqualToString:[self DateBecomeString:[myGetDateBefore firstObject]]]);
    NSLog(@"%d",[[self DateBecomeString:[myGetDate lastObject]]isEqualToString:[self DateBecomeString:[myGetDateBefore lastObject]]]);
    
    NSArray *arr = [_pickDateBeforeString componentsSeparatedByString:@"-"];
    NSArray *arr1 = [_pickDateString componentsSeparatedByString:@"-"];
    
    if ([[self DateBecomeString:[myGetDate firstObject]]isEqualToString:[self DateBecomeString:[myGetDateBefore firstObject]]]&&[[self DateBecomeString:[myGetDate lastObject]]isEqualToString:[self DateBecomeString:[myGetDateBefore lastObject]]]) {
        NSLog(@"在同一周");
        blnToday = YES;
        SwipeWay = YES;
        
        
    }else{
        if (arr.count == 3&&arr1.count == 3) {
            if ([[arr objectAtIndex:0] integerValue]<[[arr1 objectAtIndex:0] integerValue]) {//年份上次选择的年份大于选择的年份说明向左
                SwipeWay = NO;
                NSLog(@"上次选择的年份大于选择的年份说明向左");
            }else if([[arr objectAtIndex:0] integerValue]>[[arr1 objectAtIndex:0] integerValue]){//上次小于选择年份向右
                SwipeWay = YES;
                NSLog(@"上次小于选择年份向右");
            }else{//年份相等，判断月份
                NSLog(@"年份相等");
                if ([[arr objectAtIndex:1] integerValue]<[[arr1 objectAtIndex:1] integerValue]) {//上次月份小于选中月份向左
                    SwipeWay = NO;
                    NSLog(@"上次月份小于选中月份向左");
                    
                }else if([[arr objectAtIndex:1] integerValue]>[[arr1 objectAtIndex:1] integerValue]){
                    
                    SwipeWay = YES;
                    NSLog(@"上次月份大于选中月份向左");
                }else{//月份相等，判断日期
                    //                NSLog(@"%@%@%@%@",startDate,endDate,_pickDate,_pickDateBefore);
                    
                    
                    NSLog(@"月份相等");
                    if ([[arr objectAtIndex:2] integerValue]<[[arr1 objectAtIndex:2] integerValue]) {
                        SwipeWay = NO;
                        NSLog(@"当前日期大于选中日期");
                    }else if([[arr objectAtIndex:2] integerValue]>[[arr1 objectAtIndex:2] integerValue]){
                        SwipeWay = YES;
                        NSLog(@"当前日期小于选中日期");
                    }else{//选择了当前日期
                        
                        SwipeWay = NO;
                        NSLog(@"当前日期等于选中日期");
                    }
                }
            }
        }
    }
    //向右是yes，向左是NO，today是yes
    //    [_calendarView delegateSwipeAnimation:NO blnToday:blnToday selectedDate:startDate];
    [_calendarView delegateSwipeAnimation:SwipeWay blnToday:blnToday selectedDate:_pickDate];
    
    _backgroundView.hidden = YES;
#pragma mark - 选择时间end
    
}
-(void)returnSelectDateBlock{
    
}

#pragma mark - 取消按钮
- (void)cancelBtnClick:(UIButton *)sender{
    NSLog(@"取消");
    NSLog(@"%@%@",_pickDate,_pickDateString);
    
    _backgroundView.hidden = YES;
}

#pragma mark - she zhi dang qian zhou de qi dian
-(NSString *)setStartDateStr{
    NSString *str = [self getWeekTime:YES];
    _startDateStr = str;
    
    return _startDateStr;
}

#pragma mark - she zhi dang qian zhou de zhong dian
-(NSString *)setEndDateStr{
    NSString *str = [self getWeekTime:NO];
    _endDateStr = str;
    return _endDateStr;
}

#pragma mark - quchudangqianzhou
- (NSString *)getWeekTime:(BOOL)start
{
    NSDate *nowDate = [NSDate date];
    NSCalendar *calendar = [NSCalendar currentCalendar];
    NSDateComponents *comp = [calendar components:NSYearCalendarUnit | NSMonthCalendarUnit | NSDayCalendarUnit | NSWeekdayCalendarUnit | NSDayCalendarUnit fromDate:nowDate];
    // 获取今天是周几
    NSInteger weekDay = [comp weekday];
    // 获取几天是几号
    NSInteger day = [comp day];
    NSLog(@"%ld----%ld",weekDay,day);
    
    // 计算当前日期和本周的星期一和星期天相差天数
    long firstDiff,lastDiff;
    //    weekDay = 1;
    if (weekDay == 1)
    {
        firstDiff = -6;
        lastDiff = 0;
    }
    else
    {
        firstDiff = [calendar firstWeekday] - weekDay + 1;
        lastDiff = 8 - weekDay;
    }
    NSLog(@"firstDiff: %ld   lastDiff: %ld",firstDiff,lastDiff);
    
    // 在当前日期(去掉时分秒)基础上加上差的天数
    NSDateComponents *firstDayComp = [calendar components:NSYearCalendarUnit | NSMonthCalendarUnit | NSDayCalendarUnit  fromDate:nowDate];
    [firstDayComp setDay:day + firstDiff];
    NSDate *firstDayOfWeek = [calendar dateFromComponents:firstDayComp];
    
    NSDateComponents *lastDayComp = [calendar components:NSYearCalendarUnit | NSMonthCalendarUnit | NSDayCalendarUnit   fromDate:nowDate];
    [lastDayComp setDay:day + lastDiff];
    NSDate *lastDayOfWeek = [calendar dateFromComponents:lastDayComp];
    
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    [formatter setDateFormat:@"yy-MM-dd"];
    NSString *firstDay = [formatter stringFromDate:firstDayOfWeek];
    NSString *lastDay = [formatter stringFromDate:lastDayOfWeek];
    NSLog(@"%@=======%@",firstDay,lastDay);
    
    if (start) {
        return firstDay;
    }else{
        return lastDay;
    }
    //    NSString *dateStr = [NSString stringWithFormat:@"%@-%@",firstDay,lastDay];
    //
    //    return dateStr;
    
}
-(void)dataRequest{
    NSMutableDictionary *parama = [[NSMutableDictionary alloc]init];
    NSArray *arrSubDUrlStr;
    if(_model.menuPageUrl){
        
        arrSubDUrlStr= [[NSString stringWithFormat:@"%@", _model.menuPageUrl] componentsSeparatedByString:@"="]; // [self.dataDic valueForKey:@"menuPageUrl"]
    }else{
        arrSubDUrlStr= [[NSString stringWithFormat:@"%@", [self.dataDic valueForKey:@"menuPageUrl"]] componentsSeparatedByString:@"="]; //
        
    }
    NSString *tableIdStr = @"";
    
    for (int i = 0; i < arrSubDUrlStr.count; i++) {
        NSString *str = arrSubDUrlStr[i];
        if ([str hasSuffix:@"tableId"]) {
            NSString *finalStr = arrSubDUrlStr[i+1];
            
            tableIdStr = [finalStr componentsSeparatedByString:@"&"][0];
        }
    }
    
    //#ifdef Main
    
    //#ifdef Main
    if([getUIStyle() isEqualToString:STYLE0]){
        //
        //        [parama setObject:tableIdStr forKey:@"tableId"];
#pragma mark - 放开课程表
        [parama setObject:@"2" forKey:@"tableId"];
    }else{
        //#elif Student
        [parama setObject:@"19" forKey:@"tableId"];
    }
    //#else
    
    //#endif
    
    
    
    
    [parama setObject:[NSString stringWithFormat:@"%@", userId()] forKey:@"mainId"];
    
    
    [parama setObject:[NSString stringWithFormat:@"%@", _startDateStr] forKey:@"minDate"];
    [parama setObject:[NSString stringWithFormat:@"%@", _endDateStr] forKey:@"maxDate"];
    
    /*----  当滑动过后相当于pick日期，也需要将pick的日期修改，周为单位只需修改为这一周的任意一天就可以  ----*/
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    [dateFormatter setDateFormat:@"yyyy-MM-dd"];
    _pickDateBefore = [dateFormatter dateFromString:_startDateStr];
    _pickDateBeforeString = _startDateStr;
    
    NSString *requestStr;
    
    if([getUserType() isEqualToString:STYLE0]){
        
        requestStr = [NSString stringWithFormat:@"%@%@", self.programaUrl, KECHENGBIAO_URl];
    }else{
        requestStr = [NSString stringWithFormat:@"%@%@", self.programaUrl, KECHENGBIAO_URl];//上元学员修改
    }
    
    
    
    [NetRequest requestUrl:requestStr andParamas:parama andReturnBlock:^(NSData *data, NSError *error) {
        if (!error&&data!=nil) {
            id obj = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
            NSLog(@"%@", obj);
            
            if ([obj valueForKey: @"promptMessage"]) {
                [[NSNotificationCenter defaultCenter]postNotificationName:@"relogin" object:@"relogin"];
                return ;
            }
            
            [self dataUse:obj];
            if(isNew==YES){
                [self searchCondition];
            }
        }else{
            NSString *string = [NSString stringWithFormat:@"%@", error.localizedDescription];
            [self showLabelWithText:string];
        }
    }];
}


-(void)dataUse:(id)obj{
    _mutArr = [[NSMutableArray alloc]init];
    
    NSArray *array =[obj valueForKey:@"dataInfo"];
    
    if(array.count!=0){
        for (NSDictionary *dic in array) {
            CouModel *model = [[CouModel alloc]init];
            model = [model initWithDictionary:dic error:nil];
            
            if([model.classtype isEqualToString:@"模考"]){//模考
                model.type = 2;
                model.colorNum = 0xA79FFC;
            }else if([model.classtype isEqualToString:@"模考讲解"]){//模考讲解
                model.type = 3;
                model.colorNum = 0xA79FFC;
            }else if([model.classtype isEqualToString:@"课程"]){//一对一
                model.type = 1;
                model.colorNum = 0x7FABFC;
            }else if([model.classtype isEqualToString:@"助教"]){//助教（不确定）
                model.type = 4;
                model.colorNum = 0xFBC137;
            }
            
            model.colorNum = 0x0ae1a8;
            
            [_mutArr addObject:model];
        }
    }
    _arr = [NSMutableArray arrayWithArray:_mutArr];
    //    CouModel *model = _arr[0];
    //    NSLog(@"%@",model.stuName);
    [self writeData];
    
}

-(void)drawLine{
    _line = [[LineView alloc] init];
    _line.backgroundColor = [UIColor whiteColor];
    //    if(KWIDTH<375){
    //         _line.frame = CGRectMake(0, 70, KWIDTH, KHEIGHT+600);
    //    }else{
    _line.frame = CGRectMake(0, 65, KWIDTH, KHEIGHT+1100);
    //    }
    [_line setNeedsDisplay];
    [self.timeTableSV addSubview:_line];
    if (!_yearLabel) {
        _yearLabel = [[UILabel alloc] init];
        [_line addSubview:_yearLabel];
        _yearLabel.textColor = [UIColor colorWithRed:0 green:0 blue:0 alpha:0.03];
        _yearLabel.font = [UIFont systemFontOfSize:140];
        [_yearLabel mas_makeConstraints:^(MASConstraintMaker *make) {
            make.centerX.equalTo(self.view.mas_centerX).offset(15);
            make.centerY.equalTo(self.view.mas_centerY);
        }];
    }
    [_line sendSubviewToBack:_yearLabel];
}

//Initialize
-(CLWeeklyCalendarView *)calendarView
{
    if(!_calendarView){
        _calendarView = [[CLWeeklyCalendarView alloc] initWithFrame:CGRectMake(20, -10, self.view.bounds.size.width-25, CALENDER_VIEW_HEIGHT-25)];
        _calendarView.delegate = self;
        
    }
    
    return _calendarView;
}


-(void)dailyCalendarViewDidSelect:(NSDate *)date
{
    NSLog(@"%@",date);
    
    //    NSString *str = [df stringFromDate:_pickDate];
    _pickDateBefore = _pickDate;
    _pickDateBeforeString = _pickDateString;
    [self AmethodForSavePickDate:date];
    //    _pickDate = date;
    //    str = [df stringFromDate:_pickDate];
    //    _pickDateString = str;
    //zzz表示时区，zzz可以删除，这样返回的日期字符将不包含时区信息。
    
    //    [dateFormatter setDateFormat:@"yyyy-MM"];
    
    //    NSString *destDateString = [dateFormatter stringFromDate:date];
}

-(void)timeTable{
    NSString *timeTablePath = [[NSBundle mainBundle]pathForResource:@"json" ofType:@"txt"];
    NSMutableArray *mutArr = [[NSMutableArray alloc]init];
    _arr = [[NSMutableArray alloc]init];
    //    NSString *str = [[NSString alloc]initWithContentsOfFile:timeTablePath];
    //    NSDictionary *dic = [[NSDictionary alloc]initWithContentsOfFile:timeTablePath];
    //    _arr = [dic objectForKey:@"item"];
    NSData *data = [[NSMutableData alloc] initWithContentsOfFile:timeTablePath];
    NSDictionary *jsonDic = [NSJSONSerialization JSONObjectWithData:data options:0 error:nil];
    NSArray *array = [jsonDic objectForKey:@"rows"];
    
    for (NSDictionary *dic in array) {
        CouModel *model = [[CouModel alloc]init];
        model = [model initWithDictionary:dic error:nil];
        //        model.appoint = [dic valueForKey:@"AFM_3"];
        //         model.name = [dic valueForKey:@"AFM_43"];
        //         model.teacher = [dic valueForKey:@"AFM_44"];
        //         model.time = [dic valueForKey:@"AFM_45"];
        //         model.start = [dic valueForKey:@"AFM_3"];
        //         model.appoint = [dic valueForKey:@"AFM_4"];
        //         model.end = [dic valueForKey:@"AFM_5"];
        //         model.appointHour = [dic valueForKey:@"AFM_8"];
        //         model.mockMachine = [dic valueForKey:@"AFM_49"];
        //        model.dudaocishu = [dic valueForKey:@"AFM_53"];
        //        model.stuName = [dic valueForKey:@"AFM_61"];
        //        model.comlateHomeWork = [dic valueForKey:@"AFM_62"];
        //        model.homeWorkScore = [dic valueForKey:@"AFM_64"];
        //         model.school = [dic valueForKey:@"AFM_46"];
        //         model.state = [dic valueForKey:@"DIC_AFM_9"];
        //        model.stage = [dic valueForKey:@"AFM_18"];
        //        model.userHour = [dic valueForKey:@"AFM_48"];
        //        model.stuToTeacher = [dic valueForKey:@"AFM_74"];
        //        model.teacherToStu = [dic valueForKey:@"DIC_AFM_70"];
        //        model.teacherToPar = [dic valueForKey:@"AFM_72"];
        //         model.firstTest = [dic valueForKey:@"AFM_58"];
        if([[dic allKeys]containsObject:@"AFM_51"]){//模考
            model.type = 2;
        }else if([[dic allKeys]containsObject:@"AFM_49"]){//模考讲解
            model.type = 3;
        }else if([[dic allKeys]containsObject:@"AFM_18"]){//一对一
            model.type = 1;
        }else if([[dic allKeys]containsObject:@"DIC_AFM_54"]){//助教（不确定）
            model.type = 4;
        }
        
        
        
        [mutArr addObject:model];
    }
    _arr = [NSMutableArray arrayWithArray:mutArr];
    CouModel *model = _arr[0];
    NSLog(@"%@",model.stuName);
}

#pragma mark - CLWeeklyCalendarViewDelegate
-(NSDictionary *)CLCalendarBehaviorAttributes
{
    return @{
             CLCalendarWeekStartDay : @1,                 //Start Day of the week, from 1-7 Mon-Sun -- default 1
             CLCalendarDayTitleTextColor : [UIColor colorWithRed:0x88/255.0 green:0x88/255.0 blue:0x88/255.0 alpha:1
                                            ],
             CLCalendarSelectedDatePrintColor : [UIColor whiteColor],
             };
}

#pragma mark -request is here
-(void)setData{
    
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    [dateFormatter setDateFormat:@"yyyy-MM-dd"];
    _startDateStr =  [dateFormatter stringFromDate:_calendarView.startDate];
    NSString *yearStr = [[_startDateStr componentsSeparatedByString:@"-"] firstObject];
    [self setYear:yearStr];
    _endDateStr = [dateFormatter stringFromDate:_calendarView.endDate];
    [self AmethodForSavePickDate:_calendarView.startDate];
    [self dataRequest3];
    
    
    //    [self dataRequest];
}

#pragma mark - 设置年份
- (void)setYear:(NSString *)year{
    _yearLabel.text = year;
}


#pragma mark - tian xie shu ju
-(void)writeData{
    NSLog(@" ----------------------- < %@ >", _calendarView.startDate);
    NSLog(@" ----------------------- < %@ >", _calendarView.endDate);
    //*** base data request
    if(_subViewArr.count!=0){
        for(int i=0;i<_subViewArr.count;i++){
            SubView *sv = _subViewArr[i];
            
            [sv removeGestureRecognizer:_tap];
            
            [sv removeFromSuperview];
        }
        [_subViewArr removeAllObjects];
    }
    
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    [dateFormatter setDateFormat:@"yyyy-MM-dd"];
    NSString *startDateString = [dateFormatter stringFromDate:_calendarView.startDate];
    NSString *endDateString = [dateFormatter stringFromDate:_calendarView.endDate];
    NSArray *startArr = [startDateString componentsSeparatedByString:@"-"];
    //    NSArray *endArr = [endDateString componentsSeparatedByString:@"-"];
    //       [dateFormatter setTimeZone:[NSTimeZone timeZoneWithName:@"Asia/Urumqi"]];
    NSDate *startDayPre = [dateFormatter dateFromString:startDateString];
    NSDate *endDayPre = [dateFormatter dateFromString:endDateString];
    
    NSDate *startDay = [[NSDate alloc]initWithTimeInterval:8*60*60 sinceDate:startDayPre];
    NSDate *endDay = [[NSDate alloc]initWithTimeInterval:8*60*60 sinceDate:endDayPre];
    
    //    NSInteger startDate = [startArr[2] integerValue];
    //    NSInteger indexNum =
    //    for(int i=1;i<8;i++){
    //        for(int j=0;j<13;j++){
    //            if((i==xValue&&j==5)||(i==2&&j==2)){
    //                SubView *sv =[[SubView alloc]initWithFrame:CGRectMake(30+i*43, j*100, 43, 100)];
    //                [_line addSubview:sv];
    //                sv.home.text =@"托福一对一";
    //            }
    //        }
    //    }
    for(int i=0;i<[_mutArr count];i++){
        CouModel *model1 =_mutArr[i];
        //        NSString *dateStr = model1.appoint;
        
        NSString *dateLoca = [NSString stringWithFormat:@"%@",model1.appoint];
        NSTimeInterval time=[dateLoca doubleValue]/1000.0;
        NSDate *detaildate=[NSDate dateWithTimeIntervalSince1970:time];
        NSDate *dateBJTime = [[NSDate alloc]initWithTimeInterval:8*60*60 sinceDate:detaildate];//北京时间
        
        
        NSString *dateStr = [NSString stringWithFormat:@"%@", dateBJTime];
        
        NSArray *appointArr = [dateStr componentsSeparatedByString:@" "];
        //        NSArray *dateArr = [appointArr[0] componentsSeparatedByString:@"-"];
        //        NSInteger num = [dateArr[2] integerValue];
        //        NSInteger index = num-startDate+1;
        
        NSDateFormatter *formatter = [[NSDateFormatter alloc] init] ;
        [formatter setDateFormat:@"yyyy-MM-dd"];
        NSString *str = appointArr[0];
        //        NSString *time = model1.time;
        NSDate *datePre=[formatter dateFromString:str];
        NSDate *date = [[NSDate alloc]initWithTimeInterval:8*60*60 sinceDate:datePre];
        
        
        NSString *week = [self weekdayStringFromDate:date];
        NSInteger weekIndex = [week integerValue];
        
        //        NSArray *timeArr = [model1.time componentsSeparatedByString:@"-"];
        
        NSDate *dataStartTime = [self dateAdd:model1.startTime];
        NSDate *dataEndTime = [self dateAdd:model1.endTime];
        
        
        NSArray *arrL = [[NSString stringWithFormat:@"%@", dataStartTime] componentsSeparatedByString:@" "];
        NSArray *arrR = [[NSString stringWithFormat:@"%@", dataEndTime] componentsSeparatedByString:@" "];
        
        //        NSArray *timeArrStart = [model1.time componentsSeparatedByString:@"-"];
        //        NSArray *timeArrEnd = [model1.time componentsSeparatedByString:@"-"];
        
        //        NSArray *a1 =[timeArr[0]componentsSeparatedByString:@":"];
        //        NSArray *a2 =[timeArr[1]componentsSeparatedByString:@":"];
        
        NSArray *a1 =[arrL[1]componentsSeparatedByString:@":"];
        NSArray *a2 =[arrR[1]componentsSeparatedByString:@":"];
        
        NSInteger hour1 = [a1[0]integerValue];
        NSInteger hour2 = [a2[0]integerValue];
        
        NSInteger min1 = [a1[1]integerValue];
        NSInteger min2 = [a2[1]integerValue];
        
        NSInteger lastMinute= (hour2*60+min2)-(hour1*60+min1);
        // NSInteger hourNum = lastMinute/60;
        float width;
        if(KWIDTH>375){
            width = (KWIDTH-36)/7;
        }else{
            width = (KWIDTH-33)/7;
        }
        
        BOOL isBetween =[self date:date isBetweenDate:startDay andDate:endDay];
        if(isBetween){
            CouModel *model = _mutArr[i];
            NSLog(@"~~~~~~~~~~~~~~~~~~~~~~~~~~%@~~~~~~~~",model.appoint);
            NSLog(@"%ld",(long)weekIndex);
            int xaa= 0;
            if(KWIDTH<375){
                xaa = weekIndex*width-20+12;
            }else{
                xaa = weekIndex*width-20+5;
            }
            
            NSInteger class_time = lastMinute/15;//课程时长
            //            float firstPersion = min1/66;
            float half_height = (float)33/(float)2;//半个格的长度
            SubView *sv =[[SubView alloc]initWithFrame:CGRectMake(xaa, (hour1-8)*66+min1/15*half_height, width-2, half_height*class_time)];
            [_line addSubview:sv];
            sv.home.text =model1.name;
            sv.subTitle.hidden = YES;
            sv.layer.masksToBounds = YES;
            sv.layer.cornerRadius = 8.0f;
            sv.backgroundColor =[UIColor colorWithHex:model.colorNum];
            sv.state.text = [_stateDic objectForKey:model.state];
            _tap = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(tapView:)];
            
            [sv addGestureRecognizer:_tap];
            [_subViewArr addObject:sv];
            sv.tag = 100+i;
            
            //            if(lastMinute==30){
            //                if(min1==30){//30+(weekIndex-1)*width
            //
            //                    SubView *sv =[[SubView alloc]initWithFrame:CGRectMake(xaa, (hour1-8+1)*66-33+1, width-2, 33-1)];
            //                    [_line addSubview:sv];
            //                    sv.home.text =model1.name;
            //                    sv.subTitle.hidden = YES;
            //                    sv.layer.masksToBounds = YES;
            //                    sv.layer.cornerRadius = 8.0f;
            //                    sv.backgroundColor =[UIColor colorWithHex:model.colorNum];
            //                    sv.state.text = [_stateDic objectForKey:model.state];
            //                    _tap = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(tapView:)];
            //
            //                    [sv addGestureRecognizer:_tap];
            //                    [_subViewArr addObject:sv];
            //                    sv.tag = 100+i;
            //                }else{
            //
            //                    SubView *sv =[[SubView alloc]initWithFrame:CGRectMake(xaa, (hour1-8)*66+1, width-2, 33-1)];
            //                    [_line addSubview:sv];
            //                    sv.home.text =model1.name;
            //                    sv.subTitle.hidden = YES;
            //                    sv.layer.masksToBounds = YES;
            //                    sv.layer.cornerRadius = 8.0f;
            //                    sv.backgroundColor =[UIColor colorWithHex:model.colorNum];
            //                    sv.state.text = [_stateDic objectForKey:model.state];
            //
            //                    _tap = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(tapView:)];
            //
            //                    [sv addGestureRecognizer:_tap];
            //                    [_subViewArr addObject:sv];
            //                    sv.tag = 100+i;
            //                }
            //            }
            //            else{
            //                if(min1==30){
            //
            //                    SubView *sv =[[SubView alloc]initWithFrame:CGRectMake(xaa, (hour1-8)*66+33+1, width-2, 132-1)];
            //                    sv.layer.masksToBounds = YES;
            //                    sv.layer.cornerRadius = 8.0f;
            //                    [_line addSubview:sv];
            //                    sv.home.text =model1.name;
            //                    sv.subTitle.text = model.classtype;
            //                    sv.backgroundColor =[UIColor colorWithHex:model.colorNum];
            //                    sv.state.text = [_stateDic objectForKey:model.state];
            //
            //                    _tap = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(tapView:)];
            //
            //                    [sv addGestureRecognizer:_tap];
            //                    [_subViewArr addObject:sv];
            //                    sv.tag = 100+i;
            //                }else{
            //
            //                    SubView *sv =[[SubView alloc]initWithFrame:CGRectMake(xaa, (hour1-8)*66+1, width-2, 132-1)];
            //                    sv.layer.masksToBounds = YES;
            //                    sv.layer.cornerRadius = 8.0f;
            //                    [_line addSubview:sv];
            //                    sv.home.text =model1.name;
            //                    sv.subTitle.text = model.classtype;
            //                    sv.backgroundColor =[UIColor colorWithHex:model.colorNum];
            //                    sv.state.text = [_stateDic objectForKey:model.state];
            //
            //                    _tap = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(tapView:)];
            //
            //                    [sv addGestureRecognizer:_tap];
            //                    [_subViewArr addObject:sv];
            //                    sv.tag = 100+i;
            //                }
            //            }
        }
    }
    
    
    NSLog(@"123aaa");
    //zzz表示时区，zzz可以删除，这样返回的日期字符将不包含时区信息。
    
    
    
    //    NSString *destDateString = [dateFormatter stringFromDate:_calendarView.startDate];
    //    NSArray *arr = [destDateString componentsSeparatedByString:@"-"];
    //    [self setTitleText:[NSString stringWithFormat:@"%@",startArr[0]]];
    _monthLable.text =startArr[1];
    
}

-(NSDate *)dateAdd:(NSString *)date{
    NSString *dateLoca = [NSString stringWithFormat:@"%@",date];
    NSTimeInterval time=[dateLoca doubleValue]/1000.0;
    NSDate *detaildate=[NSDate dateWithTimeIntervalSince1970:time];
    NSDate *dateBJTime = [[NSDate alloc]initWithTimeInterval:8*60*60 sinceDate:detaildate];
    return dateBJTime;
}
-(BOOL)date:(NSDate*)date isBetweenDate:(NSDate*)beginDate andDate:(NSDate*)endDate
{
    if ([date compare:beginDate] == NSOrderedAscending)
        return NO;
    
    if ([date compare:endDate] == NSOrderedDescending)
        return NO;
    
    return YES;
}
#pragma mark -- 点击课程表模块
-(void)tapView:(UITapGestureRecognizer *)tap{
    
    
    CouModel *mod =_mutArr[tap.view.tag-100];
    NSLog(@"%@",mod);
    ClassDetailViewController *cdvc = [[ClassDetailViewController alloc] init];
    cdvc.model = mod;
    cdvc.cusTabView = self.cusTabView;
    [self.navigationController pushViewController:cdvc animated:YES];
    
    //    [self timeTable];
    //    OneToOneViewController *oneV = [[OneToOneViewController alloc]init];//一对一
    //
    //    MockViewController *mv= [[MockViewController alloc]init];//模考讲解
    //
    //    MockExplainViewController *mev= [[MockExplainViewController alloc]init];//模考讲解
    //
    //    AssistantViewController *asv= [[AssistantViewController alloc]init];
    //    [self.navigationController pushViewController:asv animated:YES];
    //    asv.TabView = self.TabView;
    //
    //    LeaveViewController *lv= [[LeaveViewController alloc]init];
    //    [self.navigationController pushViewController:lv animated:YES];
    //    lv.TabView = self.TabView;
    //    SubView *subView = (SubView *)[self.view viewWithTag:tap.view.tag];
    //    CouModel *model =_mutArr[tap.view.tag-100];
    //    switch (model.type) {
    //        case 0:
    //            oneV.TabView = self.TabView;
    //            oneV.model = model;
    //            [self.navigationController pushViewController:oneV animated:YES];
    //            break;
    //        case 1:
    //            oneV.TabView = self.TabView;
    //            oneV.model = model;
    //            [self.navigationController pushViewController:oneV animated:YES];
    //            break;
    //        case 2:
    //            [self.navigationController pushViewController:mv animated:YES];
    //            mv.TabView = self.TabView;
    //            mv.model = model;
    //            break;
    //        case 3:
    //            [self.navigationController pushViewController:mev animated:YES];
    //            mev.TabView = self.TabView;
    //            mev.model = model;
    //            break;
    //        case 4:
    //            [self.navigationController pushViewController:asv animated:YES];
    //            asv.TabView = self.TabView;
    //            asv.model = model;
    //            break;
    //        default:
    //            break;
    //    }
    
}

-(NSString*)weekdayStringFromDate:(NSDate*)inputDate {
    
    NSArray *weekdays = [NSArray arrayWithObjects: [NSNull null], @"7", @"1", @"2", @"3", @"4", @"5", @"6", nil];
    
    NSCalendar *calendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
    
    NSTimeZone *timeZone = [[NSTimeZone alloc] initWithName:@"Asia/Shanghai"];
    
    [calendar setTimeZone: timeZone];
    
    NSCalendarUnit calendarUnit = NSWeekdayCalendarUnit;
    
    NSDateComponents *theComponents = [calendar components:calendarUnit fromDate:inputDate];
    
    return [weekdays objectAtIndex:theComponents.weekday];
    
}
#pragma mark - seletimeTable or couresList
-(void)seleBtn1:(SeleButton *)btn{
    if(btn.selected==NO){
        btn.selected=YES;
        self.courseListBtn.selected=NO;
        [self.courseListBtn setSelectedColor:seleColor andUnSelectedColor:0xffffff];
        _timeTableSV.hidden=  NO;
        _courseListSV.hidden = YES;
        [btn setTitleColor:[UIColor colorWithHex:0xffffff]forState:UIControlStateNormal];
        [self.courseListBtn setTitleColor:[UIColor colorWithHex:seleColor]forState:UIControlStateNormal];
    }
    [btn setSelectedColor:seleColor andUnSelectedColor:0xffffff];
}

-(void)seleBtn2:(SeleButton *)btn{
    if(btn.selected==NO){
        btn.selected=YES;
        //        [self dataRequest2];
        self.timeTableBtn.selected=NO;
        [self.timeTableBtn setSelectedColor:seleColor andUnSelectedColor:0xffffff];
        _courseListSV.hidden = NO;
        _timeTableSV.hidden=  YES;
        [btn setTitleColor:[UIColor colorWithHex:0xffffff]forState:UIControlStateNormal];
        [self.timeTableBtn setTitleColor:[UIColor colorWithHex:seleColor]forState:UIControlStateNormal];
    }
    [btn setSelectedColor:seleColor andUnSelectedColor:0xffffff];
}

#pragma mark ---  NSDate-->NSString
- (NSString *)DateBecomeString:(NSDate *)date{
    NSString *str;
    NSDateFormatter *df = [[NSDateFormatter alloc] init];
    [df setDateFormat:@"yyyy-MM-dd"];
    
    str = [df stringFromDate:date];
    return str;
}
#pragma mark ---  NSString--->NSDate
- (NSDate *)StringBecomeDate:(NSString *)str{
    NSDate *date;
    NSDateFormatter *df = [[NSDateFormatter alloc] init];
    [df setDateFormat:@"yyyy-MM-dd"];
    
    date = [df dateFromString:str];
    return date;
}
#pragma mark ---将选择的日期状态保存，包括滑动后的状态
-(void)AmethodForSavePickDate:(NSDate *)date{
    //    _pickDateBeforeString = _pickDateString;
    //    _pickDateBefore = _pickDate;
    
    NSDateFormatter *df = [[NSDateFormatter alloc] init];
    [df setDateFormat:@"yyyy-MM-dd"];
    
    NSString *str = [df stringFromDate:date];
    _pickDateString = str;
    _pickDate = date;
    
}
#pragma mark ----获得某一天的星期一和星期日是哪一天
-(NSArray *)getStartDateAndEndDate:(NSDate *)date{
    NSArray *arr;
    NSCalendar *calendar = [NSCalendar currentCalendar];
    NSDateComponents *comp = [calendar components:NSYearCalendarUnit | NSMonthCalendarUnit | NSDayCalendarUnit | NSWeekdayCalendarUnit | NSDayCalendarUnit fromDate:date];
    // 获取今天是周几
    NSInteger weekDay = [comp weekday];
    NSLog(@"选中周是周几%zd",weekDay);
    // 获取几天是几号
    NSInteger day = [comp day];
    NSLog(@"%ld----%ld",(long)weekDay,(long)day);
    
    // 计算当前日期和本周的星期一和星期天相差天数
    long firstDiff,lastDiff;
    //    weekDay = 1;
    if (weekDay == 1)
    {
        firstDiff = -6;
        lastDiff = 0;
    }
    else
    {
        firstDiff = [calendar firstWeekday] - weekDay + 1;
        lastDiff = 8 - weekDay;
    }
    NSLog(@"firstDiff: %ld   lastDiff: %ld",firstDiff,lastDiff);
    
    // 在当前日期(去掉时分秒)基础上加上差的天数
    NSDateComponents *firstDayComp = [calendar components:NSYearCalendarUnit | NSMonthCalendarUnit | NSDayCalendarUnit  fromDate:date];
    [firstDayComp setDay:day + firstDiff];
    NSDate *firstDayOfWeek = [calendar dateFromComponents:firstDayComp];
    
    NSDateComponents *lastDayComp = [calendar components:NSYearCalendarUnit | NSMonthCalendarUnit | NSDayCalendarUnit   fromDate:date];
    [lastDayComp setDay:day + lastDiff];
    NSDate *lastDayOfWeek = [calendar dateFromComponents:lastDayComp];
    
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    [formatter setDateFormat:@"yyyy-MM-dd"];
    NSString *firstDay = [formatter stringFromDate:firstDayOfWeek];
    NSString *lastDay = [formatter stringFromDate:lastDayOfWeek];
    NSLog(@"%@=======%@",firstDay,lastDay);
    //    _startDateStr = firstDay;
    //    _endDateStr = lastDay;
    NSDate *startDate = [formatter dateFromString:firstDay];
    NSDate *endDate = [formatter dateFromString:lastDay];
    arr = @[startDate,endDate];
    return arr;
}


@end
